package com.example.demotest.demos.bens;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelExample {
    public static void main(String[] args) {
        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建一个工作表(sheet)
        Sheet sheet = workbook.createSheet("ExampleSheet");

        // 创建行（0基索引）
        Row row = sheet.createRow(0);

        // 创建单元格并设置值
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello");
        cell = row.createCell(1);
        cell.setCellValue("World");
        // 创建行（0基索引）
        Row row2 = sheet.createRow(1);
        Cell cell2 = row2.createCell(0);
        cell2.setCellValue("你好");
        cell2 = row2.createCell(2);
        cell2.setCellValue("测试！");
        // 写入到文件
        try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 确保工作簿被关闭以释放资源
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}